import FormSolutionApi from "@/api/form/core/formSolution";
import DialogBox from "@/assets/js/DialogBox";
import FormPdfHtml from "@/views/modules/form/core/FormPdfHtml";
import {Util} from "@lowcode/jpaas-common-lib";
import FormPrintLodopApi from "@/api/form/core/formPrintLodop";
import PublicApi from "@/api/form/core/public";

export default {
    data(){
        return {
            lodopUtil:{}
        }
    },
    methods:{
        getButtonObj(btn){
            for(let i=0;i<this.buttons.length;i++){
                if(this.buttons[i].idx_==btn.idx_){
                    return this.buttons[i];
                }
            }
            return btn;
        },
        async handMethod(btn) {
            await this.handFormMethod(this.getButtonObj(btn));
        },
        async handFormMethod(btn) {
            btn.loading=true;
            let rxForm=this.$refs.rxForm;
            var res=await FormSolutionApi.validPreByButton(btn.preCondConfig,JSON.stringify(rxForm.getData()));
            if(!res.success){
                btn.loading=false;
                this.$message.error(res.message);
                return;
            }
            btn.loading=false;
            //表单方法
            if(btn.type=="formMethod"){
                var method =  btn.method;
                var formVm = rxForm.formVm;
                if (formVm && formVm[method]) {
                    formVm[method](this,btn);
                }
                return;
            }else if(btn.type=="custom"){//自定义方法
                let formJson = rxForm.getData();
                let rxAjax = this.rxAjax;
                let config=btn.config;
                let func=new Function("formJson","rxAjax",config.action).bind(this);
                func(formJson,rxAjax);
                return;
            }
            //调用预定义方法。
            this[btn.method](btn);
        },
        i18n(name,text,key){
            return this.$ti18(name,text,"formSolution",key);
        },
        /**
         * 打开表单。
         * @param btn
         */
        openSolutionForm(btn) {
            let self_ = this;
            let formJson = {};
            let config=btn.config.openConfig;
            let openFormConfig = btn.config.openFormConfig
            let rxForm=this.$refs.rxForm;
            let formVm=rxForm.formVm;
            formJson[formVm.alias] = rxForm.getData();
            let data=formJson[formVm.alias];
            let initData=this.getInitData(config,data);
            DialogBox.showForm({
                title: config.formName,
                curVm: self_,
                data: {
                    alias: config.formAlias, setInitData: function (data) {
                        return Object.assign(data, initData);
                    },
                    closeOnSave:true
                },
                max: openFormConfig.isMax == "YES" ? true : false,
                shade: openFormConfig.model,
                widthHeight:[openFormConfig.width + 'px', openFormConfig.height + 'px'],

            }, function (action,data) {
                if(formVm[config.callback]){
                    formVm[config.callback](action,data);
                }
            });
        },
        //获取打开表单的初始化数据
        getInitData(config,data){
            let formData={};
            //根据配置 构建映射数据
            if(config.formConfig){
                let formConfig=JSON.parse(config.formConfig);
                for (let i = 0; i < formConfig.length; i++) {
                    let obj=formConfig[i];
                    if(!obj.fieldConfig || obj.fieldConfig.length==0){
                        continue;
                    }
                    for (let j = 0; j < obj.fieldConfig.length; j++) {
                        let fieldConfig=obj.fieldConfig[j];
                        //映射到主表
                        if(obj.targetType=="main"){
                            //当前主表
                            if(fieldConfig.curType=="main"){
                                formData[fieldConfig.targetField]=data[fieldConfig.curField];
                            }else  if(fieldConfig.curType=="onetoone"){ //当前一对一子表
                                formData[fieldConfig.targetField]=data["sub__"+fieldConfig.curTable][fieldConfig.curField];
                            }
                        }else if(obj.targetType=="onetoone"){//映射到一对一子表
                            //一对一子表无数据时默认{}
                            if(!formData["sub__"+obj.targetTable]){
                                formData["sub__"+obj.targetTable]={};
                            }
                            //当前主表
                            if(fieldConfig.curType=="main"){
                                formData["sub__"+obj.targetTable][fieldConfig.targetField]=data[fieldConfig.curField];
                            }else  if(fieldConfig.curType=="onetoone"){ //当前一对一子表
                                formData["sub__"+obj.targetTable][fieldConfig.targetField]=data["sub__"+fieldConfig.curTable][fieldConfig.curField];
                            }
                        }else if(obj.targetType=="onetomany") {//映射到一对多子表
                            if(!formData["sub__"+obj.targetTable]){
                                formData["sub__"+obj.targetTable]=[];
                            }
                            if(!formData.initData){
                                formData.initData={}
                            }
                            //子表一行的初始化数据
                            if(!formData.initData[obj.targetTable]){
                                formData.initData[obj.targetTable]={};
                            }
                            //当前主表
                            if(fieldConfig.curType=="main"){
                                formData.initData[obj.targetTable][fieldConfig.targetField]=data[fieldConfig.curField];
                                if(formData["sub__"+obj.targetTable] && formData["sub__"+obj.targetTable].length>0){
                                    for (let k = 0; k < formData["sub__"+obj.targetTable].length; k++) {
                                        formData["sub__"+obj.targetTable][k][[fieldConfig.targetField]]=data[fieldConfig.curField];
                                    }
                                }
                            }else  if(fieldConfig.curType=="onetoone"){ //当前一对一子表
                                formData.initData[obj.targetTable][fieldConfig.targetField]=data["sub__"+fieldConfig.curTable][fieldConfig.curField];
                                if(formData["sub__"+obj.targetTable] && formData["sub__"+obj.targetTable].length>0){
                                    for (let k = 0; k < formData["sub__"+obj.targetTable].length; k++) {
                                        formData["sub__"+obj.targetTable][k][[fieldConfig.targetField]]=data["sub__"+fieldConfig.curTable][fieldConfig.curField];
                                    }
                                }
                            }else {//当前一对多子表
                                if(!data["sub__"+fieldConfig.curTable]){
                                    continue;
                                }
                                for (let k = 0; k < data["sub__"+fieldConfig.curTable].length; k++) {
                                    let row=data["sub__"+fieldConfig.curTable][k];
                                    //一对多子表单行无数据时默认{}
                                    if(!formData["sub__"+obj.targetTable][k]){
                                        let subRow=JSON.parse(JSON.stringify(formData.initData[obj.targetTable]));
                                        subRow[fieldConfig.targetField]= row[fieldConfig.curField];
                                        formData["sub__"+obj.targetTable][k]=subRow;
                                    }else {
                                        formData["sub__"+obj.targetTable][k][fieldConfig.targetField]=row[fieldConfig.curField];
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return formData;
        },
        /**
         * 打开自定义表单。
         * @param btn
         */
        openCustomForm(btn) {
            let self_ = this;
            let formJson = {};
            let config=btn.config;
            let formVm=this.$refs.rxForm;
            formJson[formVm.formVm.alias] = formVm.getData();
            FormSolutionApi.getValueByCustomFormConfig({
                formJson: formJson,
                formConfig: config.formConfig || []
            }).then(res => {
                DialogBox.showForm({
                    title: config.formName,
                    curVm: self_,
                    data: {
                        alias: config.formAlias, setInitData: function (data) {
                            return Object.assign(data, res);
                        }
                    },
                    max: true
                }, function (action) {
                });
            })
        },
        /**
         * 打开列表
         */
        openCustomList(btn){
            let config=btn.config;
            var values=this.$refs.rxForm.getData()
            var params=config.params
            var queryParams=[]
            var typeJson = {string: "S", int: "I", date: "D", float: "F"};
            for(let param of params){

                let srcField=param.srcField.toLowerCase();
                if(!srcField){
                    continue;
                }
                var tablePre = param.tablePre ? param.tablePre + "." : "";
                var type = typeJson[param.dataType] ? typeJson[param.dataType] : "S";
                var queryString = "Q_" + tablePre + param.destField + "_" + type + "_" + param.fieldOp;
                var tmp = queryString + "=" + values[srcField];
                queryParams.push(tmp);
            }

            //获取数据权限
           let listConfig=JSON.parse(btn.config.listConfig);
           if (listConfig.pmtAlias){
               let pmtAlias="pmtAlias="+listConfig.pmtAlias
               queryParams.push(pmtAlias);
           }

            var self_=this
            var listConf = {
               curVm:this,
               max:listConfig.isMax == "YES" ? true : false,
               shade:listConfig.model,
            }
            if(listConfig.isMax == "NO"){
                listConf["widthHeight"] = [listConfig.width + 'px', listConfig.height + 'px']
            }
            DialogBox.dialog({key:config.alias,params:queryParams.join("&")},{...listConf},function (action,data) {
                var rxForm=self_.$refs.rxForm
                var formVm = rxForm.formVm;
                let method=config.callBack;
                if (formVm && formVm[method]) {
                    formVm[method](action,data);
                }
            });
        },
        /**
         * pdf打印
         * @param btn
         */
        pdfPrint(btn) {
            let rxForm=this.$refs.rxForm;
            var dataJson = rxForm.getData();
            //打开pdf模板
            var self = this;
            let name=this.$i18(btn.i18nJson,"标题");
            var conf = {
                component: FormPdfHtml,
                title: name ,
                widthHeight: [`100%`, `100%`]
            }
            let btnConfig=btn.config;
            var baseConf = {
                curVm: self,
                data: {   //传递参数
                    pkId: btnConfig.defId,
                    dataJson: dataJson,
                    metadata:rxForm.metadata
                }
            }
            let config = Object.assign(baseConf, conf)
            Util.open(config, function (action) {
            })
        },
        print() {
            let formVm=this.$refs.rxForm;
            var dataJson = formVm.getData();
            var url ="/formprint/" + this.formSolutionAlias;
            var portalUrl = window.localStorage.getItem('portalUrl');
            if (portalUrl) {
                url = portalUrl + url;
            } else {
                url = process.env.VUE_APP_API_BASE_URL + url;
            }
            if (this.pkId) {
                url += "/" + this.pkId;
            }
            let appId=this.curApp.appId;
            url+="?appId="+ appId;

            window['_getFormData_'+this.formSolutionAlias]=function(){
                return dataJson;
            }
            window.open(url);
        },
        /**
         * ureport打印
         * @param btn
         */
        async ureportPrint(btn) {
            let rxForm=this.$refs.rxForm;
            var json = rxForm.getData();
            if (!json.ID_) {
                this.$message.warning(this.i18n('funcJs.ureportPrintTips','编辑状态才能打印!'));
                return;
            }
            let btnConfig=btn.config;
            //获得当前编辑数据的ID
            let btnConf=btn.conf;
            let parameter="";
            for (var item of btnConf.params) {
                if (item.returnValue){
                    if (item.valueSource=="param"){
                        //表单字段映射
                        var paramName=item.returnValue;
                        paramName=paramName.toLowerCase();
                        parameter+= '&'+item.bindFieldLabel + '=' + json[paramName] ;
                    }else if (item.valueSource=="constantVar"){
                        //常量
                        var paramMap=[]
                        paramMap.push({name:item.bindFieldLabel,valueSource:item.valueSource,valueDef:item.returnValue})
                        //调用方法替换常量值
                        let rtn=await PublicApi.getParams(JSON.stringify(paramMap))
                        if (rtn){
                            parameter+= '&'+item.bindFieldLabel + '=' + rtn[item.bindFieldLabel] ;
                        }
                    }else if (item.valueSource=="fixedVar"){
                        //固定值
                        parameter+= '&'+item.bindFieldLabel + '=' + item.returnValue ;
                    }else {
                        parameter+="";
                    }
                }

            }
            var url = "/ureport/preview?_u=qiaolin-" + btnConf.name + "&Id=" + json.ID_+parameter;
            window.open(url);
        },
        /**
         * 套打。
         * @param btn
         */
        printLodop(btn) {
            let defId=btn.config.defId;
            if (!defId) {
                this.$message.warning(this.i18n('funcJs.printLodopTips','编辑状态才能打印!'));
                return;
            }
            var files = require.context('@/utils', true, /\.js$/);
            files.keys().forEach(key => {
                if (key.indexOf('/LodopFuncs.js') != -1) {
                    this.lodopUtil = files(key).default || files(key)
                }
            })
            var self=this;
            this.lodopUtil.onload(function(lodop){
                if (!lodop) {
                    return;
                }
                //初始化任务名称
                lodop.PRINT_INIT(btn.config.name);
                FormPrintLodopApi.printHtml({
                    pkId: defId,
                    formData: JSON.stringify(self.$refs.rxForm.getData())
                }).then(res => {
                    eval(res.data);
                    //打印预览
                    lodop.PREVIEW();
                })
            })
        },
        /**
         * 删除对象空格。
         * @param _data
         */
        removeSpaces(_data) {
            //清除字段前后空格；
            for (var key in _data) {
                var item = _data[key];
                if (typeof item == "string" && item != "") {
                    _data[key] = item.trim();
                } else if (item && Object.prototype.toString.call(item) == "[object Array]") {
                    var _self = this;
                    item.forEach((item, idx) => {
                        _self.removeSpaces(item);
                    })
                } else if (item && Object.prototype.toString.call(item) == "[object Object]") {
                    this.removeSpaces(item);
                }
            }

        },
        parseButtons(res){
            this.canStartFlow = res.canStartFlow;
            this.flowInstId=res.data.INST_ID_;
            this.flowDefId=res.formSolution.flowDefId;
            let pkId=res.data[res.idField || "ID_"];
            let instStatus=res.data.INST_STATUS_;
            var temp=[];
            var btns = res.buttons ? JSON.parse(res.buttons) : [];
            for (var i = 0; i < btns.length; i++) {
                var btn = btns[i];
                if(!this.rxReadOnly){
                    //编辑
                    if(btn.mode && btn.modeConfig.indexOf("edit")==-1){
                        continue;
                    }
                }else{
                    //明细
                    if(btn.mode && btn.modeConfig.indexOf("detail")==-1){
                        continue;
                    }
                }
                if((btn.method=="startFlow" || btn.type=="flowImage") && !this.canStartFlow){
                    continue;
                }
                if(btn.method=="newSubmit" && !pkId){
                    continue;
                }
                if(btn.method=="submit" && instStatus && instStatus!='CANCEL' && instStatus!='DRAFTED'){
                    this.canStartFlow = false;
                }
                if(btn.method=="bpmPreview" && !this.canStartFlow && !pkId){
                    continue;
                }

                //如果存在绑定流程定义，则不显示暂存按钮
                if(btn.method=="staging"){
                    if(this.formSolution.flowDefMapping && this.formSolution.flowDefMapping){
                        let flowDefMapping=JSON.parse(this.formSolution.flowDefMapping);
                        if(flowDefMapping.length>0){
                            continue;
                        }
                    }
                }
                btn.loading = false;
                temp.push(btn);
            }
            return temp;
        },
        dataChange:Util.debounce(function (data){
            let self_=this;
            FormSolutionApi.getButtonsByFormJson(self_.formSolution.alias,data).then(res=>{
                self_.buttons = self_.parseButtons(res);
            })
        },500),
        /**
         * 打开自定义组件
         * @param config
         * {
         *     path:"组件路径",
         *     title:"组件标题",
         *     width: "800px",
         *     height: "600px",
         *     callback: 需要执行的脚本，脚本时字符串格式，脚本中可以使用:
         *     formData :表单数据
         *     customData：组件返回的数据。
         *     比如脚本书写如下 :
         *     'console.info(formData)'
         * }
         */
        openCustomControl(config){//打开自定义组件
            let params = config.config ;

            let rxForm=this.$refs.rxForm;

            //获取当前表单的数据
            let formData = rxForm.getData();
            let obj = {
                curVm:this,
                component:params.path,
                title:params.title,
                widthHeight:[params.width,params.height],
                data:formData
            }
            DialogBox.openComponent(obj,function (action,data){
                if(action == 'ok'){
                    let vm=null;
                    if(rxForm.formVm){
                        vm=rxForm.formVm;
                    }
                    else{
                        vm=rxForm;
                    }
                    if(vm && vm[params.callback]){
                        vm[params.callback](action,data)
                    }
                }
            })
        },

    }
}